package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Employee;
import com.itheima.bean.PageParam;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

//添加事务的注解，如果service的方法出现了异常，那么就回滚这个事务
//其实不加注解，数据也会跑到数据库去，是因为mybatis-plus背后添加事务的自动提交方式
@Transactional
@Service
public class EmployeeServiceImpl implements EmployeeService {

    //注入进来mapper
    @Autowired
    private EmployeeMapper em;

    /**
     * 登录功能
     * @param employee
     * @return
     */
    @Override
    public Employee login(Employee employee) {

        //1、创建lambda条件对象
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        //1.1对明文密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //2、组装查询条件
        lqw.eq(Employee::getUsername,employee.getUsername());
        //lqw.eq(Employee::getPassword,employee.getPassword());
        lqw.eq(Employee::getPassword,md5Password);

        //执行查询
        return em.selectOne(lqw);
    }

    /**
     * 添加功能
     * @param employee
     * @return
     */
    @Override
    public int add(Employee employee) {
        int row = em.insert(employee);
        /*System.out.println("row ======================================= " + row);
        int a = 1 / 0 ;*/
        return row;
    }

    /**
     * 分页功能
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Employee> findPage(PageParam pageParam) {
        //0、设置查询条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        //设置模糊查询,如果有传递过来姓名的信息，那么就追加按照姓名来进行模糊查询，否则这个条件就不会追加进来
        lqw.like(pageParam.getName() !=null ,Employee::getName,pageParam.getName());


        //1、设置查询第几页，每页查询多少条
        IPage<Employee> p = new Page<>(pageParam.getPage(),pageParam.getPageSize());

        //2、执行分页查询
        return em.selectPage(p,lqw);
    }

    /**
     * 修改功能
     * @param employee
     * @return
     */
    @Override
    public int update(Employee employee) {
        return em.updateById(employee);
    }
}
